﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model_SSResourceManager
{
    public class UserManager
    {
        private readonly IDataBase _dataBase;

        internal UserManager(IDataBase dataBase)
        {
            this._dataBase = dataBase;
        }

        public User Create(UserRoles role = UserRoles.User)
        {
            return new User()
                {
                    Id = Guid.NewGuid(),
                    Role = role
                };
        }

        public bool Add(User user)
        {
            return _dataBase.AddUser(user);
        }

        public bool Update(User user)
        {
            return _dataBase.UpdateUser(user);
        }

        public bool Delete(Guid id)
        {
            return _dataBase.DeleteUser(id);
        }

        public UserStatus ManageStatus(Guid userId, bool showStatus = false, UserStatus status = UserStatus.Active)
        {
            User user = this.Get(userId);
            if (!showStatus)
            {
                user.Status = status;
                this.Update(user);
            }
            return user.Status;

        }

        public Guid Login(string login, int password)
        {
            var thisUser = this.GetAll(true)
                .Where(user =>
                    user.Login.Trim() == login.Trim() &&
                    user.Password == password)
                .FirstOrDefault();
            return (thisUser != null)
                ? thisUser.Id
                : Guid.Empty;
        }

        public bool Logout(Guid id)
        {
            User user = this.Get(id);
            user.Online = false;
            return this.Update(user);
        }

        public User Get(Guid id)
        {
            return _dataBase.GetUser(id);
        }

        public List<User> GetAll(bool ActiveOnly = false)
        {
            return _dataBase.GetAllUser(ActiveOnly);
        }

        public string GetUserRole(Guid id)
        {
            return this.Get(id).Role.ToString();
        }

        public bool CheckLoginExists(string login)
        {
            return GetAll().Any(user => user.Login.Trim() == login);
        }

        public string GetUserName(Guid guid)
        {
            return Get(guid).FirstName;
        }
    }
}
